package com.song.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.song.common.constants.HttpStatus;
import com.song.common.domain.dto.LoginDto;
import com.song.common.domain.vo.LoginUserVO;
import com.song.common.exception.ServiceException;
import com.song.common.service.IUmsAuthService;
import com.song.common.utils.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class UmsAuthServiceImpl implements IUmsAuthService {

    private final AuthenticationManager authenticationManager;
    private final JwtUtil jwtUtil;

    public UmsAuthServiceImpl(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {
        this.authenticationManager = authenticationManager;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public String login(LoginDto loginDto) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getAccount(), loginDto.getPassword());
        // 调用loadUserByUsername方法
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 获取用户信息
        LoginUserVO loginUser = (LoginUserVO) authenticate.getPrincipal();
        // 如果用户信息为空，抛出异常
        if (ObjectUtil.isNull(loginUser)) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED, "认证失败！");
        }
        // 创建token，此时的token是UUID生成的字符串，前端可以通过该字符串到redis中获取用户数据
        return jwtUtil.createToken(loginUser);
    }
}
